package com.xayy.scheduled;

import com.xayy.scheduled.enums.AssessTaskStatus;
import com.xayy.scheduled.model.AssessTaskInfo;
import com.xayy.scheduled.service.AssessTaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SysJobRunner implements CommandLineRunner {


    @Autowired
    private AssessTaskInfoService sysJobService;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为正常的定时任务
        log.info("调度任务已加载开始...");
        List<AssessTaskInfo> jobList = sysJobService.getListByStatus(AssessTaskStatus.NORMAL);
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (AssessTaskInfo job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getId(),job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }

            log.info("调度任务已加载完毕...");
        }
        log.info("调度任务已加载结束...");
    }
}
